import Http from '../../../utils/http.js';
var WxParse = require('../../../utils/wxParse/wxParse.js');
let app = getApp();
var Moment = require("../../../utils/moment.js");
import { isEmpty } from '../../../utils/util.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    commodityCode: '100078',//当前商品code
    current: 0, // 索引值
    loading: false,
    commodityCommon: {},
    activeTab: 'detail',
    evalutionLoading: false,//评论加载
    evalutionLoadingComplete: false,//评论数据加载完毕
    evalutionPage: 1,//评论当前分页
    evalutionList: [],
    checkInDate: Moment(new Date()).format('YYYY-MM-DD'),
    checkOutDate: Moment(new Date()).add(1, 'day').format('YYYY-MM-DD'),
    checkInWeek: Moment(new Date()).getWeek(Moment(new Date()).format('YYYY-MM-DD')),
    checkOutWeek: Moment(new Date()).getWeek(Moment(new Date()).add(1, 'day').format('YYYY-MM-DD')),
    totalDay:1,//共几天
    isModalShow: false,
    startTime:'09:00',
    endTime: '09:00',
    product: '',//实物种类
    specifications: [],//种类分组
    finnalPriceShow: false,
    commodityCount: 1,
    bizid:"",//当前选择的规格
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      commodityCode: options.commodityCode || '100078'
    })
    this.getCommodityDetail();
    this.getCommentList();
    //设缓存缓存起来的日期
    wx.setStorage({
      key: 'CAR_SOURCE_DATE',
      data: {
        checkInDate: this.data.checkInDate,
        checkOutDate: this.data.checkOutDate,
        checkInWeek: Moment(new Date()).getWeek(this.data.checkInDate),
        checkOutWeek: Moment(new Date()).getWeek(this.data.checkOutDate)
      }
    });
  },
  //获取评论数据
  getCommentList() {
    Http.Request('GET', `/api/customer/commodity/getCommodityCommentByCode/${this.data.commodityCode}/v1?page=${this.data.evalutionPage}&size=${app.globalData.pageSize}`).then(res => {
      //返回数组为空或者返回的条数小于设定的size认为所有数据已经加载完成
      if (res && (!res.length || res.length < app.globalData.pageSize)) {
        this.setData({
          evalutionLoadingComplete: true
        })
      }
      this.setData({
        evalutionList: this.data.evalutionList.concat(res),
        evalutionLoading: false
      })
    }).catch(err => {

    })
  },
  //获取商品详情
  getCommodityDetail() {
    this.setData({
      loading: true
    })
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    Http.Request('GET', `/api/customer/commodity/getCommodityByCode/${this.data.commodityCode}/v1`).then(res => {
      this.setData({
        commodityCommon: res.commodityCommon,
        loading: false,
        product: res.product || '',
        specifications: res.specifications ||[]
      })
      WxParse.wxParse('commodityDetail', 'html', this.data.commodityCommon.commodityDetail || app.globalData.defaultHtml, this, 25);
      wx.hideLoading();
    }).catch(err => {
      wx.hideLoading();
      app.globalFn.reLoad(this.getCommodityDetail, err)
    })
  },
  //显示弹窗
  showModal() {
    this.setData({
      isModalShow: true
    })
    this.selectComponent("#maskModals").showChoose()
  },
  //轮播图切换
  swiperChange(e) {
    const current = e.detail.current;
    this.setData({
      current
    })
  },
  //切换详情、评价
  tabSwitch(e) {
    const activeTab = e.currentTarget.dataset.type;
    this.setData({
      activeTab
    })
  },
  //滑动到底部
  scrollLower() {
    if (this.data.evalutionLoading || this.data.evalutionLoadingComplete) return;
    this.setData({
      evalutionLoading: true,
      evalutionPage: this.data.evalutionPage + 1
    })
    this.getCommentList()

  },
  //选择时间
  bindTimeChange(e) {
    const time = e.currentTarget.dataset.type+'Time'
    this.setData({
      [time]: e.detail.value
    })
  },
  //确认日期选择（子组件事件）
  handleDateConfirm(params){
    params = params.detail;
    this.setData({
      ...(params),
      totalDay: params.totalNight
    });
    this.selectComponent("#maskModals").hideModal();
  },
  //立即预订、
  handleBookNow() {
    this.selectComponent("#maskModalsSpec").showChoose();

  },
  //选择规格
  valueClick(e) {
    const speIndex = e.currentTarget.dataset.speindex;
    const valueIndex = e.currentTarget.dataset.index;
    let specifications = this.data.specifications
    specifications[speIndex].specValues.forEach(o => {
      o.selected = false
    });
    specifications[speIndex].specValues[valueIndex].selected = true;
    this.setData({
      specifications
    })
    let selectAll = false;
    for (let i = 0; i < specifications.length; i++) {
      selectAll = specifications[i].specValues.some(s => {
        return s.selected === true
      })
      if (!selectAll) break;
    }
    //所有的规格都选择了之后，判断产品价格
    if (selectAll) {
      let product = this.data.product;
      specifications.forEach((o, index) => {
        const columnName = o.specValues.find(s => {
          return s.selected === true
        }).specValue;
        console.log(columnName)
        product = product.filter(p => {
          return p[`column${index}`] === columnName
        })
      })
      this.setData({
        finnalPriceShow: true,
        finnalPrice: product[0].price,
        bizid: product[0].bizid
      })
    } else {
      this.setData({
        finnalPriceShow: false
      })
    }

  },
  //选好了
  handleSelectOk() {
    if (!this.data.finnalPriceShow && !isEmpty(this.data.specifications)) return;
    const specifications = this.data.specifications;
    let labels = '';
    specifications.forEach(o => {
      if (o.specValues && o.specValues.length) {
        const label = o.specValues.find(s => {
          return s.selected === true
        }).specValue;
        labels += label + ' ';
      }
    })

    wx.navigateTo({
      url: `./createOrder/index?checkInDate=${this.data.checkInDate}&checkOutDate=${this.data.checkOutDate}&totalDay=${this.data.totalDay}&commoditySellingPoint=${this.data.commodityCommon.commoditySellingPoint}&commodityName=${this.data.commodityCommon.commodityName}&commodityCode=${this.data.commodityCode}&commodityImage=${this.data.commodityCommon.commodityImage[0]}&startTime=${this.data.startTime}&endTime=${this.data.endTime}&bizid=${this.data.bizid}&labels=${labels}`
    })

  },
  //数量增加
  updateCount(e) {
    this.setData({
      commodityCount: e.detail
    })
  },
})